﻿namespace BM.Tools.WebControls.MForm
{
    using System;
    using System.Collections.Generic;

    using BM.Tools.WebControls.MForm.Controls.Items;
    using BM.Tools.WebControls.MForm.Navigation;

    /// <summary>
    /// A static class that adds some useful extension methods for the offspring item.
    /// </summary>
    public static class OffspringItemExtenstions
    {
        /// <summary>
        /// Maps the value of a leaf item to the specified type.
        /// </summary>
        /// <param name="item">
        /// The item from which the value is taken.
        /// </param>
        /// <typeparam name="T">
        /// the type to wchich the value is mapped
        /// </typeparam>
        /// <returns>
        /// the value mapped to T
        /// </returns>
        public static T GetValue<T>(this LeafItem item)
        {
            return (T)Convert.ChangeType(item.Value, typeof(T));
        }

        /// <summary>
        /// Performs selection on the selected item and returns all matching nodes.
        /// </summary>
        /// <param name="current">
        /// The current item.
        /// </param>
        /// <param name="path">
        /// The xpath-like path.
        /// </param>
        /// <returns>
        /// the enumeration of matching nodes
        /// </returns>
        public static IEnumerable<OffspringItem> Select(this OffspringItem current, string path)
        {
            var navigator = new OffspringsNavigator(current, path);
            return navigator.Select();
        }

        /// <summary>
        /// Performs selection on the selected item and returns the first matching node or null.
        /// </summary>
        /// <param name="current">
        /// The current item.
        /// </param>
        /// <param name="path">
        /// The xpath-like path.
        /// </param>
        /// <returns>
        /// the first matching node or null
        /// </returns>
        public static OffspringItem SelectSingle(this OffspringItem current, string path)
        {
            var navigator = new OffspringsNavigator(current, path);
            return navigator.SelectSingle();
        }
    }
}